import sqlalchemy as sa
from sqlalchemy import orm

from homegrownauth.model import meta

# Tables
groups_table = sa.Table(
    'groups',
    meta.metadata,
    sa.Column("uid", sa.types.Integer, primary_key=True),
    sa.Column("name", sa.types.Unicode(255), unique=True, nullable=False),
)

roles_table = sa.Table(
    'roles',
    meta.metadata,
    sa.Column("uid", sa.types.Integer, primary_key=True),
    sa.Column("name", sa.types.Unicode(255), unique=True, nullable=False),
)

users_table = sa.Table(
    'users',
    meta.metadata,
    sa.Column("uid", sa.types.Integer, primary_key=True),
    sa.Column("username", sa.types.Unicode(255), unique=True, nullable=False),
    sa.Column("password", sa.types.Unicode(255), nullable=False),
    sa.Column("group_uid", sa.types.Integer, sa.ForeignKey("groups.uid")),
)

users_roles_table = sa.Table(
    'users_roles',
    meta.metadata,
    sa.Column("user_uid", sa.Integer, sa.ForeignKey("users.uid")),
    sa.Column("role_uid", sa.Integer, sa.ForeignKey("roles.uid")),
)

class User(object):
    pass
class Group(object):
    pass

class Role(object):
    pass

orm.mapper(
    Group,
    groups_table,
    properties={
        "users": orm.relation(User)
    }
)

orm.mapper(
    User,
    users_table,
    properties={
        "roles": orm.relation(Role, lazy=True, secondary=users_roles_table),
        "group": orm.relation(Group),
    }
)

orm.mapper(
    Role,
    roles_table,
    properties={
            "users": orm.relation(User, lazy=True, secondary=users_roles_table)
    }
)
